package com.epfresh.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Selection;
import android.text.Spannable;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.epfresh.BuildConfig;
import com.epfresh.R;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.StatusEntity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.bean.ResultBean;
import com.epfresh.constant.Constant;
import com.epfresh.api.entity.*;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.User;
import com.epfresh.api.utils.InputControl;
import com.epfresh.global.BaseActivity;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.http.RequestManager;
import com.epfresh.api.utils.T;
import com.epfresh.global.BaseApplication;
import com.epfresh.global.DataManager;
import com.epfresh.global.MessageCentre;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class LoginActivity extends BaseActivity {

    public static final String TAG = "LoginActivity";
    // 手机号,验证码，密码
    private String phoneSting, passwordString;
    private EditText phoneEt;
    private EditText passwordEt;
    private ImageView look_password;
    TextView forgetTv;
    TextView registerTv;
    Intent intent;
    String phonePreString, passwordPreString;
    private TextView tv_crash,tv_rc,tv_beta;

    private boolean isRelogin;
    //type == 1,是退出登陆进入登陆页面
    private int type;

//    public static boolean isForeground;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        intent = new Intent(this, HomeActivity.class);
        SharedPreferences preferences = getSharedPreferences(Constant.USERINFO,
                Activity.MODE_PRIVATE);
        phonePreString = preferences.getString(Constant.MOBILE, "");
        passwordPreString = preferences.getString(Constant.PASSWORD, "");
        phoneEt.setText(phonePreString);
        passwordEt.setText(passwordPreString);

        phoneEt.setSelection(phoneEt.getText().length());


        forgetTv = (TextView)findViewById(R.id.forget);
        registerTv = (TextView)findViewById(R.id.register);
        forgetTv.setOnClickListener(this);
        registerTv.setOnClickListener(this);
        ivBack.setVisibility(View.VISIBLE);

        if (savedInstanceState != null){
            getIntent().putExtra("relogin",savedInstanceState.getBoolean("relogin"));
            getIntent().putExtra("type",savedInstanceState.getInt("type"));
        }
        isRelogin = getIntent().getBooleanExtra("relogin",false);
        if (!isRelogin){
            BaseApplication.loginActivityCount ++;
        }
        type = getIntent().getIntExtra("type",-1);

        int env = BuildConfig.ENV;

        if (env == 0){//正式版本
            findViewById(R.id.v_env).setVisibility(View.GONE);
        }else if (env > 0) {//测试版本
            findViewById(R.id.v_env).setVisibility(View.VISIBLE);
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putBoolean("relogin",isRelogin);
        outState.putInt("type",type);
        super.onSaveInstanceState(outState);
    }

    /**
     * 监听点击事件
     */
    boolean passwordflag = false;
    String password = "";

    public void initView(){
        setContentView(R.layout.activity_login);
        passwordEt = (EditText)findViewById(R.id.password_number);
        phoneEt = (EditText)findViewById(R.id.phone_number);
        Button sureBu = (Button) findViewById(R.id.sure);
        look_password = (ImageView)findViewById(R.id.look_password);
        FrameLayout look_frame = (FrameLayout) findViewById(R.id.look_frame);
        tv_crash = findViewById(R.id.tv_crash);
        tv_rc = findViewById(R.id.tv_rc);
        tv_beta = findViewById(R.id.tv_beta);
        tv_rc.setOnClickListener(this);
        tv_beta.setOnClickListener(this);

        sureBu.setOnClickListener(this);
        look_frame.setOnClickListener(this);
        toolbarTitle.setText("用户登录");
        actionbar.setVisibility(View.GONE);

        switchEnv();
    }
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.baseback:
                // 返回上一页

                onBackPressed();
                break;
            case R.id.look_frame:
                if (!passwordflag) {
                    look_password.setImageDrawable(getResources().getDrawable(R.mipmap.login_03_));
                    passwordEt.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    look_password.setImageDrawable(getResources().getDrawable(R.mipmap.login_03));
                    passwordEt.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                passwordflag = !passwordflag;
                passwordEt.postInvalidate();
                CharSequence text = passwordEt.getText();
                if (text != null) {
                    Spannable spanText = (Spannable) text;
                    Selection.setSelection(spanText, text.length());
                }
                break;
            case R.id.sure:
                if (InputControl.isEmpty(phoneEt)) {
                    T.toast("请输入手机号");
                    return;
                }
                if (!InputControl.isPhoneNumber(phoneEt)) {
                    T.toast("请输入正确的手机号");
                    return;
                }
                if (InputControl.isEmpty(passwordEt)) {
                    T.toast("请输入密码");
                    return;
                }
                login();
                break;
            case R.id.forget:
            /* 找回密码，忘记密码 */
                Intent intentforgetPasd = new Intent(getApplicationContext(),
                        ForgetPasdActivity.class);
                String ph = "";
                if (phoneEt.getText() != null && !"".equals(phoneEt.getText().toString())) {
                    ph = phoneEt.getText().toString();
                }
                intentforgetPasd.putExtra("tel", ph);// 将手机号码传过去
                intentforgetPasd.putExtra("title", "找回密码");
                startActivity(intentforgetPasd);
                break;
            case R.id.register:
            /* 注册 */
                Intent intentregistertPasd = new Intent(getApplicationContext(),
                        RegisterActivity.class);
                startActivity(intentregistertPasd);
                break;
            case R.id.tv_rc:
                ApplicationHelper.getInstance().switchEnv(1);
                tv_crash.setText("切换环境(当前是预发布环境)");
                T.toast("已切换到预发布环境");
                break;
            case R.id.tv_beta:
                ApplicationHelper.getInstance().switchEnv(2);
                tv_crash.setText("切换环境(当前是测试环境)");
                T.toast("已切换到测试环境");
                break;
            default:
                break;
        }
    }

    private void switchEnv() {
        int env0 = ApplicationHelper.getInstance().getEnv();
        if (env0 == 1) {
            tv_crash.setText("切换环境(当前是预发布环境)");
        } else if (env0 == 2) {
            tv_crash.setText("切换环境(当前是测试环境)");
        }
    }

    @Override
    public void onBackPressed() {


        if (type == 1){
            Intent main = new Intent(getApplicationContext(), HomeActivity.class);
            main.putExtra("home_tab_index",0);
            main.putExtra("re_type",type);
            main.putExtra("isLogin",true);
            startActivity(main);
            finish();
            Log.e("sadfasf","sadfasdf");
        }else{
            super.onBackPressed();
        }
    }

    OnRequestListener<User> onRequestListener = new OnRequestListener<User>() {
        @Override
        public User jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, User.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<User> response, Object tag) {
            hideProgressDialog();
            User user = response.getResponseElement();
            user.setPhone(phoneEt.getText()
                    .toString());
            user.setPassword(passwordEt.getText()
                    .toString());
            user.setTag(UUID.randomUUID().toString());
            updateUser(user);


            SharedPreferences sp = getSharedPreferences(
                    com.epfresh.constant.Constant.USERINFO, Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putString(com.epfresh.constant.Constant.MOBILE, phoneEt.getText()
                    .toString());
            editor.putString(com.epfresh.constant.Constant.PASSWORD, passwordEt.getText()
                    .toString());
            editor.putString("accountId", user.getAccountId());
            editor.putString("access_token", user.getAccess_token());

            editor.commit();
            MessageCentre.getInstance().sendAlias(user.getPhone());

            /*
            * 判断用户是否已经完善信息；
            * 可以考虑加本地过滤，一次完善则不再次校验；节省一次网络请求，但是无法多次让用户完善并后续修改该信息；
            * */
            //isCompleted();
            //return;

            isCompleted();


        }
    };

    /**
     * 登录
     */
    private void login() {

        RequestEntityPurchase<Map<String, String>> data = new RequestEntityPurchase<>();
        data.setCmd(AppPurchaseRouterConstant.cmd_account_acc_login);
      //  data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
        Map<String, String> map = new HashMap<>();
        map.put("username", phoneEt.getText().toString());
        map.put("password", passwordEt.getText().toString());

        map.put("clientId", "purchase-android");
        map.put("clientSecret", "purchase-android-secret");
        map.put("scope", "purchase-android");

        data.setParameters(map);
        String phone = getUser().getPhone();
        /*if (phoneEt.getText().toString().trim().equals(phone)){
            requestTag.action = 1;
        }else {
            requestTag.action = -1;
        }*/
        request(data, AppPurchaseRouterConstant.cmd_account_acc_login, onRequestListener);
    }
    @Override
    protected void onDestroy() {
        RequestManager.getInstance().cancel("login");
        onRequestListener = null;
        BaseApplication.loginActivityCount --;
        if (BaseApplication.loginActivityCount < 0){
            BaseApplication.loginActivityCount = 0;
        }
        super.onDestroy();
    }

/*
    *//**
     * 判断是否需要完善信息
     *//*
    private void isCompleted() {

        final RequestEntityMap requestEntity = new RequestEntityMap();
        requestEntity.setCmd("account/isCompleted");
        RequestTag requestTag = new RequestTag();
        request(requestEntity, requestTag, new OnRequestListener<ResultBean>() {
            @Override
            public ResultBean jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, ResultBean.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                toast("服务器出现小故障，请稍后重试");
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                toast("服务器出现小故障，请稍后重试");
            }

            @Override
            public void onStart(Object tag) {
            }

            @Override
            public void onResponse(ResponseEntity<ResultBean> response, Object tag) {
                ResultBean responseElement = response.getResponseElement();
                if (responseElement.isResult()) {
                    //在重新登录后，是同一账号，才会退回到上一页
                    if (isRelogin){// && requestTag.action > 0){
                        //setReloginBack(false);

                        setResult(RESULT_OK);
                        finish();
                        return;
                    }

                    Intent main = new Intent(getApplicationContext(), HomeActivity.class);
                    int index = getIntent().getIntExtra("home_tab_index", -1);
                    if (type == 1){
                        main.putExtra("re_type",1);
                        main.putExtra("home_tab_index",0);
                    }
                    if (index > -1){
                        main.putExtra("home_tab_index",index);
                    }
                    main.putExtra("isLogin",true);
                    com.epfresh.api.entity.City city = ApplicationHelper.getInstance().getCity();
                    if(city!=null){
                        main.putExtra("cityId", city.getCityId());
                        main.putExtra("cityName", city.getCityName());
                    }
                    startActivity(main);
                    finish();
                }else {
                    Intent complete = new Intent(getApplicationContext(), PerfectInfoActivity.class);
                    complete.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(complete);
                    //finish();
                }

            }
        });
    }*/

    /**
     * 判断是否需要完善信息
     */
    public void isCompleted() {
        if (ApplicationHelper.getInstance().getUser().getAccess_token() == null) {
            return;
        }
        RequestEntityMap requestEntity = new RequestEntityMap();
        requestEntity.setCmd(AppPurchaseRouterConstant.cmd_account_acc_isCompleted);
        RequestTag requestTag = new RequestTag();
        request(requestEntity, requestTag, new OnRequestListener<ResultBean>() {
            @Override
            public ResultBean jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, ResultBean.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
            }

            @Override
            public void onStart(Object tag) {
            }

            @Override
            public void onResponse(ResponseEntity<ResultBean> response, Object tag) {
                ResultBean responseElement = response.getResponseElement();
                if (!responseElement.isResult()) {
                    Intent complete = new Intent(LoginActivity.this, PerfectInfoActivity.class);
                    complete.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(complete);
                } else {
                    DataManager.getInstance().updateCartCnt();
                    //在重新登录后，是同一账号，才会退回到上一页
                    if (isRelogin){// && requestTag.action > 0){
                        //setReloginBack(false);
                        setResult(RESULT_OK);
                        finish();
                        return;
                    }

                    Intent main = new Intent(getApplicationContext(), HomeActivity.class);
                    int index = getIntent().getIntExtra("home_tab_index", -1);
                    if (type == 1){
                        main.putExtra("re_type",1);
                        main.putExtra("home_tab_index",0);
                    }
                    if (index > -1){
                        main.putExtra("home_tab_index",index);
                    }
                    main.putExtra("isLogin",true);
                    startActivity(main);
                    finish();
                }

            }
        });
    }
}
